package com.jinxin.platform.cdqzsqacs.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jinxin.platform.base.common.pojo.JsonResult;
import com.jinxin.platform.cdqzsqacs.bean.CdqzsqacsDevice;
import com.jinxin.platform.cdqzsqacs.bean.gaEntity.Ga_cjsbxx;
import com.jinxin.platform.cdqzsqacs.common.Constant;
import com.jinxin.platform.cdqzsqacs.mapper.CdqzsqacsDeviceMapper;
import com.jinxin.platform.cdqzsqacs.service.GaUploadService;
import com.jinxin.platform.cdqzsqacs.service.IQzsqAcsDeviceService;
import com.jinxin.platform.cdqzsqacs.task.ResultEntity;
import com.jinxin.platform.cdqzsqacs.task.ServerConfig;
import com.jinxin.platform.cdqzsqacs.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.util.concurrent.ListenableFuture;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Future;

/**
 * All rights Reserved, Designed By www.beonelot.com
 *
 * @version: V1.0
 * @Copyright: www.beonelot.com Inc. All rights reserved.
 * @Description：
 * @Date: 2021-01-28
 * @Author: Lingnan
 **/
@Slf4j
@Service
public class QzsqAcsDeviceServiceImpl implements IQzsqAcsDeviceService {
    @Autowired
    private CdqzsqacsDeviceMapper deviceMapper;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private GaUploadAsyncService gaUploadAsyncService;

    @Override
    public List<CdqzsqacsDevice> list(HashMap param) {
        return deviceMapper.list(param);
    }

    @Override
    public List<CdqzsqacsDevice> listPage(HashMap param) {
        return deviceMapper.listPage(param);
    }

    @Override
    public int listPageCount(HashMap param) {
        return deviceMapper.listPageCount(param);
    }

    @Override
    public JsonResult delete(String id) {
        if(StringUtils.isEmpty(id)){
            return JsonResult.error("id不存在");
        }
        int result = deviceMapper.deleteByKey(id);
        if(result > 0){
            return JsonResult.ok("删除成功","");
        }
        return JsonResult.error("删除失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult saveOrUpdate(CdqzsqacsDevice deviceInfo) {
        if (deviceInfo == null){
            return JsonResult.error("参数错误，操作失败");
        }
        String id = deviceInfo.getId();
        int count;
        String msg = "";
        if(!StringUtils.isEmpty(deviceInfo.getDeviceNo())){
            deviceInfo.setProductCode(deviceInfo.getDeviceNo());
        }
        if(StringUtils.isEmpty(id)){
            deviceInfo.setCreateTime(LocalDateTime.now());
            deviceInfo.setId(StringUtil.getUuid());
            count = deviceMapper.insert(deviceInfo);
            msg = "新增成功";
        }else {
            count = deviceMapper.updateByKey(deviceInfo);
            msg = "更新成功";
            String communityIds = deviceInfo.getCommunityId();
            if(!StringUtils.isEmpty(communityIds)){
                String[] comIdArr = communityIds.split(",");
                String operateAdd = "add";
                String operateUpdate = "update";
                String serverPort = serverConfig.getServerPort() + "";
                String sblx = deviceInfo.getSbly()+"";
                String lx = !StringUtils.isEmpty(sblx) ? sblx : Constant.DEVICE_TYPE_SMART_ACS;
                String operateType1 = deviceInfo.getOperateType();
                String operateType = StringUtils.isEmpty(operateType1) ? operateAdd : operateUpdate;
                List<Ga_cjsbxx> gaCjsbxxList = new ArrayList<>();
                Ga_cjsbxx cjsbxx = Ga_cjsbxx.builder().CJSBXXBZ(deviceInfo.getId()).SBMC(deviceInfo.getNickName())
                        .PPXH(Constant.DEVICE_PPXH).SBLX(lx).WLDKH(serverPort).XQXXBZ(comIdArr[0])
                        .SFZX_PDBZ("1").CJXTXXBZ("").SSQY(Constant.DEVICE_SSQY).SJLY(Constant.DEVICE_SYLY).OPERATE_TYPE(operateType).build();
                gaCjsbxxList.add(cjsbxx);
                String jsonString = JSON.toJSONString(gaCjsbxxList);
                gaUploadAsyncService.gaUploadData("ga_cjsbxx", jsonString,false,"");
                deviceInfo.setOperateType(operateAdd);
                deviceMapper.updateByKey(deviceInfo);
                log.info("成功上传设备({})至公安平台." , deviceInfo.getDeviceName());
            }
        }
        if(count > 0){
            return JsonResult.ok(msg,"");
        }else {
            return JsonResult.error("操作失败，请重试");
        }
    }

    @Override
    public JsonResult batchUpdateByIds(CdqzsqacsDevice deviceInfo) {
        if (deviceInfo == null || StringUtils.isEmpty(deviceInfo.getParams())){
            return JsonResult.error("参数错误，操作失败");
        }
        String idStr = deviceInfo.getParams();
        JSONObject jsonObject = JSONObject.parseObject(idStr);
        if(jsonObject.containsKey("rIds")) {
            String idArr = jsonObject.getString("rIds");
            List<String> idList = JSONArray.parseArray(idArr, String.class);
            if (idList.size() > 0) {
                deviceInfo.setIdList(idList);
            }
        }
        int count = deviceMapper.batchUpdateByIds(deviceInfo);
        if(count > 0){
            return JsonResult.ok("设置成功","");
        }else {
            return JsonResult.error("操作失败，请重试");
        }
    }
}
